﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Fluid.Controls;
using System.Drawing;
using PasswordSafe.Classes;
using PasswordSafe.Xml;
using PasswordSafe.Encryption;
using PasswordSafe.Properties;

namespace PasswordSafe
{
    public class Browser : FluidPanel, ICommandContainer
    {
        public static  Browser Instance { get; private set; }

        const int ButtonPanelSize = 48;

        protected override void InitControl()
        {
            Instance = this;
            base.InitControl();
            BackColor = Color.Transparent;
            //DoubleBuffered = true;
            Bounds = new Rectangle(0, 0, 240, 300);
            Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
            pages = new Pages();
            pages.SelectedIndexChanged += new EventHandler<ChangedEventArgs<int>>(pages_SelectedIndexChanged);
            pages.Bounds = new Rectangle(0, 0, Width, Height - ButtonPanelSize);
            pages.Anchor = AnchorStyles.None;

            buttonPanel = new ButtonPanel();
            buttonPanel.Bounds = new Rectangle(0, pages.Bounds.Bottom, Width, ButtonPanelSize);
            buttonPanel.Anchor = AnchorStyles.None;
            buttonPanel.Command += new EventHandler<CommandEventArgs>(buttonPanel_Command);
            buttonPanel.Buttons[0].Enabled = false;

            Controls.Add(pages);
            Controls.Add(buttonPanel);
        }


        void pages_SelectedIndexChanged(object sender, ChangedEventArgs<int> e)
        {
            buttonPanel.Buttons[0].Image = e.NewValue == 1 ? Resources.search : Resources.searchd;
            buttonPanel.Buttons[0].Enabled = e.NewValue == 1;
        }

        public NotifyList Categories { get { return pages.Categories; } }

        public NotifyList Passwords { get { return pages.Passwords; } }


        void buttonPanel_Command(object sender, CommandEventArgs e)
        {
            switch (e.Command)
            {
                case "A":
                    pages.ShowSearchPanel();
                    break;

                case "B":
                    CancelChanges();
                    break;

                case "C":
                    SavePasswords();
                    break;

                case "D":
                    LogOut();
                    break;
            }
        }

        /// <summary>
        /// Cancels all changes that where made.
        /// </summary>
        public void CancelChanges()
        {
            ListBuilder.Instance.Modified = false;
        }



        public void LogOut()
        {
            SavePasswords();
            PasswordForm.Instance.Login.Visible = true;
            Close(ShowTransition.FromBottom);
        }

        /// <summary>
        /// Saves the passwords if anything was modified.
        /// </summary>
        /// <returns>True, if the passwords where saved, otherwise false.</returns>
        public bool SavePasswords()
        {
            bool result = false;
            ListBuilder listBuilder = ListBuilder.Instance;
            if (listBuilder.Modified)
            {
                Host.Cursor = Cursors.WaitCursor;
                using (PasswordWriter writer = new PasswordWriter())
                {
                    string xml = writer.Write(listBuilder.Categories, listBuilder.Passwords);
                    byte[] encrypted = Encryptor.Encrypt(xml, Encryptor.Password);

                    string compare = Encryptor.Decrypt(encrypted, Encryptor.Password);
                    if (compare != xml)
                    {
                        MessageDialog.Show("Error:\nDid not save changes, because the data cannot be decrypted.", null, "OK", Color.DarkRed);
                    }
                    else
                    {
                        DataReader.WriteData(encrypted);
                        listBuilder.UnModified();
                        result = true;
                    }
                }
                Host.Cursor = Cursors.Default;
            }
            else result = true;
            return result;
        }

        private Pages pages;
        private ButtonPanel buttonPanel;


        protected override void OnSizeChanged(Size oldSize, Size newSize)
        {
            base.OnSizeChanged(oldSize, newSize);
            if (pages == null) return;
            if (Width < Height)
            {
                int h = ScaleX(ButtonPanelSize);
                pages.Bounds = new Rectangle(0, 0, Width, Height - h);
                buttonPanel.Bounds = new Rectangle(0, pages.Bounds.Bottom, Width, h);
            }
            else
            {
                int w = ScaleX(ButtonPanel.ButtonWidth + 8 + 8);
                pages.Bounds = new Rectangle(0, 0, Width - w, Height);
                buttonPanel.Bounds = new Rectangle(pages.Bounds.Right, 0, w, Height);
            }

        }

        public override void OnPaint(FluidPaintEventArgs e)
        {
            base.OnPaint(e);
        }

        public override void Focus()
        {
            pages.Focus();
        }
    }
}
